package org.example.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
 
/**
 * MQTT配置
 *
 * @author Brant
 * @since 2025-04-21
 */
@Configuration
public class MqttConfiguration {
    /**
     * MQTT配置
     */
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;

    /**
     * 创建连接工厂
     *
     * @return MQTT连接工厂
     */
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory(){
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true); //设置新会话
        options.setUserName(mqttPropertiesConfig.getUsername());
        options.setPassword(mqttPropertiesConfig.getPassword().toCharArray());
        options.setServerURIs(new String[]{mqttPropertiesConfig.getUrl()});
        factory.setConnectionOptions(options);
        return factory;
    }
 
}